﻿using BCCommon;
using BCCommon.OAEnums.WorkflowActive;
using BCEntity.OA.WorkflowActive.WorkflowActive;
using BCEntity.OA.WorkflowActive.WorkflowActivity;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCData.OA.WorkflowActivity.WorkflowActivity
{
    public class WorkflowActivityData : IWorkflowActivityData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM oa_workflowactivity";
        private const string QUERY = @"SELECT WorkflowActivityId,CompanyId,DepartmentId,AdminId,OtherUserId,AuthorFullName,RoleType,ActivityStatus,CreateAdminId,CreateAdminName,CreateTime,
                                            WorkflowCategoryId,CompleteTime,CloseTime,ClosePersonName,CloseRemark,CategoryCode,CategoryName,TemplateCode,TemplateName,TemplateIcon,TemplateDescription,
                                            WorkflowCode,WorkflowName,IsBaseWorkflow 
                                        FROM oa_workflowactivity";
        private const string PENDING_TASK_QUERY = @"SELECT A.WorkflowActivityId,A.CompanyId,A.DepartmentId,A.AdminId,A.OtherUserId,A.AuthorFullName,A.RoleType,A.ActivityStatus,A.CreateAdminId,A.CreateAdminName,
                                A.WorkflowCategoryId,A.CloseTime,A.ClosePersonName,A.CloseRemark,A.CategoryCode,A.CategoryName,A.TemplateCode,A.TemplateName,A.TemplateIcon,A.TemplateDescription,
                                A.WorkflowCode,A.WorkflowName,A.IsBaseWorkflow,
                                B.WorkflowActivityStepId,B.Step,B.StepStatus,B.StepOrder,B.IsAdditionalValidationStep,B.AllowAssignNextValidater,B.CreateTime,B.ActiveTime,
								B.CompleteTime,B.CompleteType,B.TemplateStepCode,B.StepCode,B.NodeName,B.NodeType,B.StepType,B.ExecutorId,
								B.ExecutorName,B.ExecutorType,B.RejectorId,B.RejectorName,B.RejectorType,B.RejectedRemark,B.ReplyRemark,B.TimeConsuming,B.TimeConsumingSeconds,B.AdditionalRemark
                            FROM OA_WorkflowActivity A
                            INNER JOIN OA_WorkflowActivityStep B ON A.WorkflowActivityId = B.WorkflowActivityId AND B.StepStatus IN ('Pending','Active')
                            INNER JOIN OA_WorkflowActivityStepReviewer C ON B.WorkflowActivityStepId = C.WorkflowActivityStepId";
        public WorkflowActivityData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        #region 检查工作流活动是否存在
        public async Task<bool> Exists(long workflowActivityId)
        {
            string sql = string.Format(@"{0} WHERE WorkflowActivityId=?WorkflowActivityId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityId", workflowActivityId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加工作流活动
        public async Task<WorkflowActivityEntity> Add(WorkflowActivityEntity entity)
        {
            string sql = @"INSERT INTO OA_WorkflowActivity(WorkflowCategoryId,CategoryCode,CategoryName,TemplateCode,TemplateName,WorkflowCode,WorkflowName,IsBaseWorkflow,CompanyId,DepartmentId,
                                AdminId,OtherUserId,AuthorFullName,RoleType,ActivityStatus,TemplateIcon,TemplateDescription)
                            VALUES(?WorkflowCategoryId,?CategoryCode,?CategoryName,?TemplateCode,?TemplateName,?WorkflowCode,?WorkflowName,?IsBaseWorkflow,?CompanyId,?DepartmentId,
                                ?AdminId,?OtherUserId,?AuthorFullName,?RoleType,?ActivityStatus,?TemplateIcon,?TemplateDescription)";
            sql = string.Format("{0};{1} WHERE WorkflowActivityId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowCategoryId", entity.WorkflowCategoryId, DbType.Int64, size: 20);
            parameters.Add("?CategoryCode", entity.CategoryCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 30);
            parameters.Add("?TemplateCode", entity.TemplateCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?TemplateName", entity.TemplateName?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?TemplateIcon", entity.TemplateIcon?.Trim(), DbType.AnsiString, size: 1000);
            parameters.Add("?TemplateDescription", entity.TemplateDescription?.Trim(), DbType.AnsiString, size: 400);
            parameters.Add("?WorkflowCode", entity.WorkflowCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?WorkflowName", entity.WorkflowName?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?IsBaseWorkflow", entity.IsBaseWorkflow, DbType.Boolean);
            parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32, size: 11);
            parameters.Add("?DepartmentId", entity.DepartmentId, DbType.Int32, size: 11);
            parameters.Add("?AdminId", entity.AdminId, DbType.Int64, size: 20);
            parameters.Add("?OtherUserId", entity.OtherUserId, DbType.Int64, size: 20);
            parameters.Add("?AuthorFullName", entity.AuthorFullName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?RoleType", entity.RoleType.ToString(), DbType.AnsiString);
            parameters.Add("?ActivityStatus", entity.ActivityStatus.ToString(), DbType.AnsiString);
            parameters.Add("?CreateAdminId", entity.CreateAdminId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminName", entity.CreateAdminName?.Trim(), DbType.AnsiString, size: 20);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<WorkflowActivityEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 修改工作流活动
        public async Task<WorkflowActivityEntity> Update(WorkflowActivityEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("oa_workflowactivity", new string[] { "CompanyId", "DepartmentId", "AdminId", "OtherUserId", "AuthorFullName", "RoleType", "ActivityStatus", "CreateAdminId", "CreateAdminName", "WorkflowCategoryId", "CompleteTime", "CloseTime", "ClosePersonName", "CloseRemark", "CategoryCode", "CategoryName", "TemplateCode", "TemplateName", "WorkflowCode", "WorkflowName", "IsBaseWorkflow" }, new string[] { "WorkflowActivityId" });
            sql = string.Format("{0} {1} WHERE WorkflowActivityId=?WorkflowActivityId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityId", entity.WorkflowActivityId, DbType.Int64, size: 20);
            parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32, size: 11);
            parameters.Add("?DepartmentId", entity.DepartmentId, DbType.Int32, size: 11);
            parameters.Add("?AdminId", entity.AdminId, DbType.Int64, size: 20);
            parameters.Add("?OtherUserId", entity.OtherUserId, DbType.Int64, size: 20);
            parameters.Add("?AuthorFullName", entity.AuthorFullName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?RoleType", entity.RoleType.ToString(), DbType.AnsiString);
            parameters.Add("?ActivityStatus", entity.ActivityStatus.ToString(), DbType.AnsiString);
            parameters.Add("?CreateAdminId", entity.CreateAdminId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminName", entity.CreateAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?WorkflowCategoryId", entity.WorkflowCategoryId, DbType.Int64, size: 20);
            parameters.Add("?CompleteTime", entity.CompleteTime, DbType.DateTime);
            parameters.Add("?CloseTime", entity.CloseTime, DbType.DateTime);
            parameters.Add("?ClosePersonName", entity.ClosePersonName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CloseRemark", entity.CloseRemark?.Trim(), DbType.String);
            parameters.Add("?CategoryCode", entity.CategoryCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 30);
            parameters.Add("?TemplateCode", entity.TemplateCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?TemplateName", entity.TemplateName?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?WorkflowCode", entity.WorkflowCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?WorkflowName", entity.WorkflowName?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?IsBaseWorkflow", entity.IsBaseWorkflow, DbType.Boolean);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<WorkflowActivityEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除工作流活动
        public async Task<bool> Delete(long workflowActivityId)
        {
            string sql = @"DELETE FROM oa_workflowactivity WHERE WorkflowActivityId=?WorkflowActivityId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityId", workflowActivityId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取工作流活动
        public async Task<WorkflowActivityEntity> GetEntity(long workflowActivityId)
        {
            string sql = string.Format(@"{0} WHERE WorkflowActivityId=?WorkflowActivityId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityId", workflowActivityId, DbType.Int64);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<WorkflowActivityEntity>(sql, parameters);
        }
        #endregion

        #region 获取工作流活动列表
        public async Task<IEnumerable<WorkflowActivityEntity>> GetList()
        {
            return await this.databaseContext.Master.QueryAsync<WorkflowActivityEntity>(QUERY);
        }
        #endregion

        #region 获取工作流活动分页（待处理任务）
        public async Task<(IEnumerable<WorkflowActivityViewEntity>, int)> PendingHandleTaskQuery(long adminId, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            wheres.Add("C.AdminId=?AdminId");
            parameters.Add("?AdminId", adminId, DbType.Int64);
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("B.CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("B.CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("B.CreateTime>=?Start AND B.CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }

            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM OA_WorkflowActivity A
                            INNER JOIN OA_WorkflowActivityStep B ON A.WorkflowActivityId = B.WorkflowActivityId AND B.StepStatus IN ('Pending','Active')
                            INNER JOIN OA_WorkflowActivityStepReviewer C ON B.WorkflowActivityStepId = C.WorkflowActivityStepId {1};",
                  PENDING_TASK_QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "B.CreateTime" : string.Format("B.{0}", sortName),
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.QueryMultipleAsync<WorkflowActivityViewEntity, int>(sql, parameters);
        }
        #endregion

        #region 获取工作流活动分页（我发起的，已完成，已关闭）
        public async Task<(IEnumerable<WorkflowActivityViewEntity>, int)> Query(long? adminId, long? userId, OAActivityStatus? activityStatus, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (adminId.HasValue)
            {
                wheres.Add("AdminId=?AdminId");
                parameters.Add("?AdminId", adminId.Value, DbType.Int64);
            }
            if (userId.HasValue)
            {
                wheres.Add("OtherUserId=?UserId");
                parameters.Add("?UserId", userId.Value, DbType.Int64);
            }
            if (activityStatus.HasValue)
            {
                wheres.Add("ActivityStatus=?ActivityStatus");
                parameters.Add("?ActivityStatus", activityStatus.Value.ToString(), DbType.AnsiString);
            }

            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM oa_workflowactivity {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.QueryMultipleAsync<WorkflowActivityViewEntity, int>(sql, parameters);
        }
        #endregion

        public async Task<int> UpdateClosed(long workflowActivityId, OAActivityStatus activityStatus, string remark)
        {
            return await databaseContext.Master.ExecuteAsync(@"UPDATE OA_WorkflowActivity 
                        SET ActivityStatus = ?ActivityStatus,
                        CloseTime = ?CloseTime,
                        CloseRemark = ?CloseRemark 
                        WHERE WorkflowActivityId = ?WorkflowActivityId",
                        new { ActivityStatus = activityStatus.ToString(), CloseTime = DateTime.Now, CloseRemark = remark, workflowActivityId });
        }
    }
}
